﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Petshop.Backend.Data
{
    class ItemRepository : Petshop.Backend.Data.IItemRepository, IDisposable
    {
        private readonly IDatabaseSession _databaseSession;

        public ItemRepository(IDatabaseSession databaseSession)
        {
            _databaseSession = databaseSession;
        }
        public Item RetrieveById(string itemId)
        {
            return _databaseSession.Context.Items.Include("Product").SingleOrDefault(c => c.ItemId == itemId);
        }
        public IEnumerable<Item> RetrieveByProductId(string productId)
        {
            return _databaseSession.Context.Items.Include("Product").Where(c => c.ProductId == productId);
        }
        public bool VerifyAvailability(string itemId, int cartItemQuantity)
        {
            var item = _databaseSession.Context.Items.SingleOrDefault(c => c.ItemId == itemId);
            return item != null && item.InventoryQty - cartItemQuantity >= 0;
        }
        public void DecreaseStockForItem(string itemId, int quantity)
        {
            var item = _databaseSession.Context.Items.SingleOrDefault(c => c.ItemId == itemId);
            if (item != null)
            {
                item.InventoryQty -= quantity;
                _databaseSession.Context.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Modified);
            }
        }
        public void Save()
        {
            _databaseSession.Context.SaveChanges();
        }
        #region IDisposable
        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _databaseSession.Context.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion






    }
}
